<?php
class AccountController extends BaseController
{
    public function __construct($uri)
    {
        parent::__construct($uri);
    }

    private function index()
    {
        if(isset($_COOKIE['access_token'])) {
            $m = new UserModel();
            //todo catch
            $token = $m->decryptToken($_COOKIE['access_token']); //todo move to __construct
            $user = $m->get($token['user_id']);
            $this->output['data']['user'] = $user;
            $this->output['tpl'] = 'accounts/index';
            return $this->output;
        }
        $this->output['http']['status_code'] = 302;
        $this->output['http']['uri'] = 'http://www.doubanxia.com/accounts/login';
        return $this->output;
    }

    private function login()
    {
        //todo check login jump
        $this->output['tpl'] = 'accounts/login';
        $this->output['data'] = array(
            'app_conf' => array(
                'douban' => $this->conf->get('douban', 'app'),
                'qq' => $this->conf->get('qq', 'app'),
            ),
        );
        return $this->output;
    }

    private function logout()
    {
        setcookie('access_token', '', -1, '/', '.doubanxia.com');
        $this->output['http']['status_code'] = 302;
        $this->output['http']['uri'] = 'http://www.doubanxia.com/accounts/login';
        return $this->output;
    }

    public function route()
    {
        if(1 === preg_match('/^\/accounts$/', $this->uri)) {
            switch($this->http_method) {
                case 'get' :
                    $this->output['http']['status_code'] = 302;
                    $this->output['http']['uri'] = 'http://www.doubanxia.com/accounts/';
                    return $this->output;
                    break;
            }
        }

        if(1 === preg_match('/^\/accounts\/$/', $this->uri)) {
            switch($this->http_method) {
                case 'get' :
                    return $this->index();
                    break;
            }
        }

        if(1 === preg_match('/^\/accounts\/login$/', $this->uri)) {
            switch($this->http_method) {
                case 'get' :
                    return $this->login();
                    break;
            }
        }

        if(1 === preg_match('/^\/accounts\/logout$/', $this->uri)) {
            switch($this->http_method) {
                case 'get' :
                    return $this->logout();
                    break;
            }
        }

        if(1 === preg_match('/^\/accounts\/(douban|qq)\/login$/', $this->uri)) {
            $tmp = explode('/', $this->uri);
            switch($this->http_method) {
                case 'get' :
                    return $this->partnerLogin($tmp[2]);
                    break;
            }
        }

        //if(1 === preg_match('/^\/accounts\/(douban|qq)\/login_back\?.+/', $this->uri)) {
        if(1 === preg_match('/^\/accounts\/douban\/login_back\?.+/', $this->uri)) {
            $tmp = explode('/', $this->uri);
            switch($this->http_method) {
                case 'get' :
                    return $this->partnerLoginBack($tmp[2]);
                    break;
            }
        }
 
        if(1 === preg_match('/^\/accounts\/qq\/login_back\?.+/', $this->uri)) {
            $tmp = explode('/', $this->uri);
            switch($this->http_method) {
                case 'get' :
                    $this->output['http']['status_code'] = 202;
                    $this->output['tpl'] = '202';
                    return $this->output;
                    break;
            }
        }
        throw new Exception(); //ControllerException();
    }

    private function partnerLogin($partner_name)
    {
        $target = '/';
        if(isset($_SERVER['HTTP_REFERER']) && ($_SERVER['HTTP_REFERER'] != 'http://www.doubanxia.com/accounts/login')) {
            $target = $_SERVER['HTTP_REFERER'];
        }
        setcookie('as', $target, time() + 86400, '/accounts'); //不要把cookie都种在根域名。所以这里种在本域名。
        $partner_app_conf = $this->conf->get($partner_name, 'app');
        $this->output['http']['status_code'] = 302;
        switch($partner_name) {
            case 'douban' :
                $this->output['http']['uri'] = 'https://www.douban.com/service/auth2/auth?client_id=' . $partner_app_conf['api_key'] . '&redirect_uri=' . urlencode($partner_app_conf['redirect_uri']) . '&response_type=code';
                break;
            case 'qq' :
                $this->output['http']['uri'] = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=' . $partner_app_conf['app_id'] . '&redirect_uri=' . urlencode($partner_app_conf['redirect_uri']);
                break;
            default :
                throw new Exception(); //todo
        }
        return $this->output;
    }

    private function partnerLoginBack($partner_name)
    {
        $params = array('code');
        $this->checkParams($params);
        $m = new UserModel();
        $token = $m->getToken($partner_name, $this->input['code']);
        $app_conf = $this->conf->get('app', 'app');
        $deadline = time() + $app_conf['access_token_ttl'];
        setcookie('access_token', $token, $deadline, '/', '.doubanxia.com'); //todo sso www.doubanxia.com
        $this->output['http']['status_code'] = 302;
        $target = '/';
        if(isset($_COOKIE['as'])) {
            $target = $_COOKIE['as'];
        }
        setcookie('as', '', -1, '/accounts');
        $this->output['http']['uri'] = $target;
        return $this->output;
    }

    /**
     * id从uri中获得
     * web server判断静态文件是否存在，如果不存在进入php
     * 触发请求豆瓣api获得名称和评分，保存到数据库
     * 静态化
     * 用户上传种子后，bt静态化，异步(todo)：重新请求豆瓣api，更新名字和评分
     * 登录按钮用js检测cookie，pt用ajax
     */
    public function get($id) {
        var_dump($this->input);
    }
}
?>
